package juc.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量
 * 应用场景:可以用于做流量控制，特别是公用资源有限的应用场景
 */
public class SemaphoreTest {
    // 信号量
    static Semaphore semaphore = new Semaphore(3);
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 20; i++) {
            final int num = i;
            threadPool.execute(()->{
                try {
                    semaphore.acquire();// 默认是1
                    //semaphore.acquire(1);
                    /*
                    boolean b = semaphore.tryAcquire(1);
                    if (!b) {
                        System.out.println(Thread.currentThread().getName()+",没有获取到许可:" + num);
                        return;
                    }
                     */
                    System.out.println(Thread.currentThread().getName()+",执行逻辑:" + num);
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
//                    semaphore.release();
                    semaphore.release(1);
                }
            });
        }
        threadPool.shutdown();
    }


}
